<template>
  <div>
    <!--引用表格-->
   <BasicTable @register="registerTable" :rowSelection="rowSelection" :expandedRowKeys="expandedRowKeys" @expand="handleExpand">
      <!-- 内嵌table区域 begin -->
           <template #expandedRowRender="{record}">
             <a-tabs tabPosition="top">
               <a-tab-pane tab="工单信息" key="installationOrder" forceRender>
                  <installationOrderSubTable v-show="isShowingInstallationOrder" :id="expandedRowKeys[0]"/>
                  <maintainOrdersSubTable v-show="isShowingMaintainOrders" :id="expandedRowKeys[0]"/>
               </a-tab-pane>
			   <a-tab-pane tab="工单流程" key="workOrderProcess" forceRender>
                  <workOrderProcessSubTable :id="expandedRowKeys[0]"/>
               </a-tab-pane>
               <a-tab-pane tab="工单回执" key="workOrderReceipt" forceRender>
                 <workOrderReceiptSubTable :id="expandedRowKeys[0]"/>
               </a-tab-pane>
               <a-tab-pane tab="现场签到" key="attendanceRecord" forceRender>
                 <attendanceRecordSubTable :id="expandedRowKeys[0]"/>
               </a-tab-pane>
			   <a-tab-pane tab="服务记录" key="workServiceRecords" forceRender>
                  <workServiceRecordsSubTable :id="expandedRowKeys[0]"/>
               </a-tab-pane>
               <a-tab-pane tab="工单回访" key="followUp" forceRender>
                 <followUpSubTable :id="expandedRowKeys[0]"/>
               </a-tab-pane>

             </a-tabs>
           </template>
     <!-- 内嵌table区域 end -->
     <!--插槽:table标题-->
      <template #tableTitle>
          <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined" v-if="hasPermission('workOrder:add')"> 新增维护单</a-button>
		   <a-button type="primary" @click="handleAddB" preIcon="ant-design:plus-outlined" v-if="hasPermission('workOrder:add')"> 新增安装单</a-button>
          <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
          <j-upload-button  type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
          <a-dropdown v-if="selectedRowKeys.length > 0">
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="batchHandleDelete">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button>批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>
       <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
        <template v-if="column.dataIndex==='homeAddress'">
          <!--省市区字段回显插槽-->
          {{ getAreaTextByCode(text) }}
        </template>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <MaintainOrdersModal title="维护订单"  @register="registerMaintainOrdersModal" @success="handleSuccess"></MaintainOrdersModal>
	<InstallationOrderModal title="安装订单" @register="registerInstallationOrderModal" @success="handleSuccess"></InstallationOrderModal>
	<TransferModal title="转派" @register="registerTransferModal" @success="handleSuccess"></TransferModal>
	<ServiceTimeModal title="修改上门服务时间" @register="registerServiceTimeModal" @success="handleSuccess"></ServiceTimeModal>
    <AttendanceRecordModal title="签到" @register="registerAttendanceRecordModal" @success="handleSuccess"></AttendanceRecordModal>
    <ServiceRecordsModal title="服务记录" @register="registerServiceRecordsModal" @success="handleSuccess"></ServiceRecordsModal>
    <FollowUpModal title="工单回访" @register="registerFollowUpModal" @success="handleSuccess"></FollowUpModal>
    <OrderReceiptModal title="工单回执" @register="registerOrderReceiptModal" @success="handleSuccess"></OrderReceiptModal>
    <ReceiptReviewModal title="审核回执" @register="registerReceiptReviewModal" @success="handleSuccess"></ReceiptReviewModal>
  </div>
</template>

<script lang="ts" name="work-workOrder" setup>
  import {ref, reactive, computed, unref, h} from 'vue';
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage'
  import {useModal} from '/@/components/Modal';
  import MaintainOrdersModal from './components/MaintainOrdersModal.vue'
  import InstallationOrderModal from './components/InstallationOrderModal.vue'
  import TransferModal from '../transfer/components/TransferModal.vue'
  import ServiceTimeModal from '../serviceTime/components/ServiceTimeModal.vue'
  import AttendanceRecordModal from '../attendanceRecord/components/WorkOrderModal.vue'
  import ServiceRecordsModal from '../workServiceRecords/components/WorkOrderModal.vue'
  import MaintainOrdersSubTable from './subTables/MaintainOrdersSubTable.vue'
  import InstallationOrderSubTable from './subTables/InstallationOrderSubTable.vue'
  import WorkOrderProcessSubTable from './subTables/WorkOrderProcessSubTable.vue'
  import WorkServiceRecordsSubTable from '../workServiceRecords/subTables/WorkServiceRecordsSubTable.vue'
  import AttendanceRecordSubTable from '../signIn/subTables/AttendanceRecordSubTable.vue'
  import WorkOrderReceiptSubTable from '../orderReceipt/subTables/WorkOrderReceiptSubTable.vue'
  import FollowUpSubTable from '../followUp/subTables/FollowUpSubTable.vue'
  import FollowUpModal from '../followUp/components/WorkOrderModal.vue'
  import OrderReceiptModal from '../orderReceipt/components/WorkOrderModal.vue'
  import ReceiptReviewModal from '../receiptReview/components/WorkOrderModal.vue'
  import {columns, searchFormSchema, superQuerySchema} from './WorkOrder.data';
  import {list, deleteOne, batchDelete, getImportUrl,getExportUrl,takingOrders} from './WorkOrder.api';
  import {downloadFile} from '/@/utils/common/renderUtils';
  import { getAreaTextByCode } from '/@/components/Form/src/utils/Area';
  import { useUserStore } from '/@/store/modules/user';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();
  const queryParam = reactive<any>({});
   // 展开key
  const expandedRowKeys = ref<any[]>([]);
  const isShowingInstallationOrder = ref(false);
  const isShowingMaintainOrders = ref(false);
  const stripedsr = ref(false);
  //注册model
  const [registerMaintainOrdersModal, {openModal: openMaintainOrdersModal}] = useModal();
  const [registerInstallationOrderModal, { openModal: openInstallationOrderModal }] = useModal();
  const [registerTransferModal, { openModal: openTransferModal }] = useModal();
  const [registerServiceTimeModal, { openModal: openServiceTimeModal }] = useModal();
  const [registerAttendanceRecordModal, { openModal: openAttendanceRecordModal }] = useModal();
  const [registerServiceRecordsModal, { openModal: openServiceRecordsModal }] = useModal();
  const [registerFollowUpModal, { openModal: openFollowUpModal }] = useModal();
  const [registerOrderReceiptModal, { openModal: openOrderReceiptModal }] = useModal();
  const [registerReceiptReviewModal, { openModal: openReceiptReviewModal }] = useModal();
  const userStore = useUserStore();
   //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '工单信息',
            api: list,
           columns,
           canResize:false,
		    bordered2: true,//默认是true，可不设置
			striped:stripeds2(),  // 表格斑马纹
		   rowClassName:'trcolor',
		   rowSelection2:{
				type: "radio"
			},
		   style33: {
    // 背景色设置为浅灰色
				backgroundColor: '#ff0000',
			},
           formConfig: {
                //labelWidth: 120,
                schemas: searchFormSchema,
                autoSubmitOnEnter:true,
                showAdvancedButton:true,
                fieldMapToNumber: [
                ],
                fieldMapToTime: [
                ],
            },
           actionColumn: {
               width: 120,
               fixed:'right'
           },
           beforeFetch: (params) => {
             if (params.licensePlate){
             params.licensePlate= '*'+params.licensePlate+'*';
             console.log("params.licensePlate=",params.licensePlate)
             }
             if (params.customerName){
               params.customerName= '*'+params.customerName+'*';
             }
             if (params.contacts){
               params.contacts= '*'+params.contacts+'*';
             }
             if (params.telephone){
               params.telephone= '*'+params.telephone+'*';
             }
             console.log("queryParam=",queryParam)
             return Object.assign(params, queryParam);
           },
        },
        exportConfig: {
            name:"工单信息",
            url: getExportUrl,
            params: queryParam,
        },
        importConfig: {
            url: getImportUrl,
            success: handleSuccess
        },
    })

  const [registerTable, {reload},{ rowSelection, selectedRowKeys }] = tableContext

   // 高级查询配置
   const superQueryConfig = reactive(superQuerySchema);

   /**
   * 高级查询事件
   */
   function handleSuperQuery(params) {
     Object.keys(params).map((k) => {
       queryParam[k] = params[k];
     });
     reload();
   }

   /**
     * 展开事件
     * */
   function handleExpand(expanded, record){
		if(record.workOrderType==1){
		   isShowingInstallationOrder.value = true;
		   isShowingMaintainOrders.value = false;
		}else if(record.workOrderType==2){
		   isShowingInstallationOrder.value = false;
		   isShowingMaintainOrders.value = true;
		}
        expandedRowKeys.value=[];
        if (expanded === true) {
           expandedRowKeys.value.push(record.id)
        }
    }
   /**
    * 新增事件
    */
  function handleAdd() {
     openMaintainOrdersModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
  
   /**
    * 新增事件
    */
  function handleAddB() {
     openInstallationOrderModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
  if(record.workOrderType=='2'){
	  openMaintainOrdersModal(true, {
		   record,
		   isUpdate: true,
		   showFooter: true,
		 });
  } else {
	  openInstallationOrderModal(true, {
		   record,
		   isUpdate: true,
		   showFooter: true,
		 });
	  }
   }
    /**
    * 转派事件
    */
  function handleTransfer(record: Recordable) {
    console.log("recordrecord==========",record)
	openTransferModal(true, {
	   record,
	   isUpdate: true,
	   showFooter: true,
	 });
   }
  /**
   * 服务记录事件
   */
  function handleServiceRecords(record: Recordable) {
    openServiceRecordsModal(true, {
      record,
      isUpdate: false,
      showFooter: true,
    });
  }

  /**
   * 工单回执事件
   */
  function handleOrderReceipt(record: Recordable) {
    openOrderReceiptModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }

  /**
   * 审核回执事件
   */
  function handleReceiptReview(record: Recordable) {
    openReceiptReviewModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }

  /**
   * 工单回访事件
   */
  function handleFollowUp(record: Recordable) {
    openFollowUpModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
    /**
    * 预约客户修改上门服务时间事件
    */
  function handleServiceTime(record: Recordable) {
	openServiceTimeModal(true, {
	   record,
	   isUpdate: true,
	   showFooter: true,
	 });
   }
  /**
   * 签到事件
   */
  function handleSignIn(record: Recordable) {
    openAttendanceRecordModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }

   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
    if(record.workOrderType=='2'){
		  openMaintainOrdersModal(true, {
		   record,
		   isUpdate: true,
		   showFooter: false,
		 });
	  }else{
		openInstallationOrderModal(true, {
		   record,
		   isUpdate: true,
		   showFooter: false,
		 });
	  }
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
    /**
   * 接单事件
   */
  async function handleTakingOrders(record) {
    await takingOrders({id: record.id}, handleSuccess);
  } 
   
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value},handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }
   /**
      * 操作栏
      */
  function getTableAction(record){
  
       return [
         {
           label: '详情',
           onClick: handleDetail.bind(null, record),
         }
       ]
   }
   function stripeds2(){
   return true;
   }

      function setDataCss(record) {
        let className = 'trcolor';
        const dataVersion1 = record.dataVersion1;
        const dataVersion2 = record.dataVersion2;
        if (dataVersion1 != dataVersion2) {
          return className;
        }
      }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record){
    const dropDownAction = reactive({
      handleList: []
    });
    if(record.workOrderStatus==12) {
      dropDownAction.handleList.push({
          label: '回访',
          onClick: handleFollowUp.bind(null, record),
        })
      // const dropDownAction = reactive({
      //   handleList: [{
      //     label: '编辑',
      //     onClick: handleEdit.bind(null, record),
      //   },]
      // });
      // dropDownAction.handleList.push({
      //   label: '转派',
      //   onClick: handleTransfer.bind(null, record),
      // });
    }
    if(record.workOrderStatus!=12 && record.workOrderStatus!=13 && hasPermission('workOrder:add')) {
      dropDownAction.handleList.push({
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          })
      dropDownAction.handleList.push({
        label: '转派',
        onClick: handleTransfer.bind(null, record),
      });
    }
    if(record.workOrderStatus==17) {
      dropDownAction.handleList.push({
        label: '回执',
        onClick: handleOrderReceipt.bind(null, record),
      });
      dropDownAction.handleList.push({
        label: '服务记录',
        onClick: handleServiceRecords.bind(null, record),
      });
    } else if(record.workOrderStatus==9) {
      dropDownAction.handleList.push({
        label: '回执审核',
        onClick: handleReceiptReview.bind(null, record),
      });
      dropDownAction.handleList.push({
        label: '服务记录',
        onClick: handleServiceRecords.bind(null, record),
      });
    } else if(record.workOrderStatus==16) {
      dropDownAction.handleList.push({
        label: '签到',
        onClick: handleSignIn.bind(null, record),
      });
    } else if(record.workOrderStatus==15){
      dropDownAction.handleList.push({
        label: '预约客户',
        onClick: handleServiceTime.bind(null, record),
      });
      dropDownAction.handleList.push({
        label: '服务记录',
        onClick: handleServiceRecords.bind(null, record),
      });
    } else if(record.workOrderStatus==3){
      dropDownAction.handleList.push({
        label: '接单',
        popConfirm: {
          title: '是否确认接单',
          confirm: handleTakingOrders.bind(null, record),
          placement: 'topLeft',
        }
      });
    }
    return dropDownAction.handleList;
  //this.backgroundColor.value='#ff0000';
		/*return [{
			label: '删除',
			popConfirm: {
			  title: '是否确认删除',
			  confirm: handleDelete.bind(null, record),
			  placement: 'topLeft',
			}
		  }
		]*/
  }

</script>

<style scoped>
.trcolor {
background-color: rgba(255, 192, 203, 0.31);
color: red;
}
</style>
